YAHOO.namespace("draftrack.status.infiniteScrolling");

//need these parameters tio be defined using in the HTML code
//js_infiniteScrollBaseUrl
//js_statusListId

YAHOO.draftrack.status.infiniteScrolling = function() {
	//threshold from the bottom of the page where the call should be made to the back end
	var threshold = 100;
	//indicator set to true when number of items is reached
	var limitReached = false;
	//identifier of the list that caontains the items
	var listId = '';
	//Limitations of the number of call at the same time
	var callOngoing = false;
	//Base URL to perform the call, just need to add the identifier at the end
	var baseUrl = '';
	
	//asynchronous call to the front end to get the result
	var responseSuccess = function(o) {
		var data = YAHOO.lang.JSON.parse(o.responseText);
		if(data.nbStatuses == 0) {limitReached = true;callOngoing = false;return;}
		
		document.getElementById(listId).innerHTML +=  data.htmlString;
		callOngoing = false;
	};
 
	var responseFailure = function(o) {
		alert('issue occured');
		callOngoing = false;
	};
 
	var callback = {
		success:responseSuccess,
  		failure:responseFailure
	};

	var loadNewItems = function (o){
		//We check the identifier of the last item
		var statusId = YAHOO.util.Dom.getLastChild(document.getElementById(listId)).id.substring(6);
		//We get the SAP from the form action
		var sUrl =  baseUrl+statusId+'/';
		var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
	};

	var scrollTest = function(){
		if(limitReached || callOngoing) return;
		
		winHeight = YAHOO.util.Dom.getViewportHeight();
		docHeight = YAHOO.util.Dom.getDocumentHeight();
		
		if  (docHeight-document.documentElement.scrollTop-winHeight <= threshold ){
		   callOngoing = true;
		   loadNewItems();
		}
	};
	
	//initialisation of the parameters
	var collectData = function(){
		baseUrl = document.getElementById('js_infiniteScrollBaseUrl').innerHTML;
		listId = document.getElementById('js_statusListId').innerHTML;
	}


	return { 
		scrollingTest:scrollTest,
		init:collectData
	        }; 
}();

//Event to get the data from the HTML page
YAHOO.util.Event.onDOMReady(YAHOO.draftrack.status.infiniteScrolling.init);

//Event that triggers the verification of the scrolling
YAHOO.util.Event.addListener(window, "scroll", YAHOO.draftrack.status.infiniteScrolling.scrollingTest);

